package top.dugou.dugou_article_zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import top.dugou.dugou_article_zuul.utils.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Zuul 的服务过滤
 * <p>Title: LoginFilter</p>
 * <p>Description: </p>
 */
@Component
public class LoginFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Resource
    private RedisUtil redisUtil;
    /**
     * 配置过滤类型，有四种不同生命周期的过滤器类型
     * 1. pre：路由之前
     * 2. routing：路由之时
     * 3. post：路由之后
     * 4. error：发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 配置过滤的顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 配置是否需要过滤：true/需要，false/不需要
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            logger.info("OPTIONS请求不做拦截操作");
            return false;
        }

        String url = request.getRequestURL().toString();
        if( Pattern.matches(".*(auth).*", url)){
            logger.info("auth请求不做拦截操作");
            return false;
        }
        return true;
    }

    /**
     * 过滤器的具体业务代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        logger.info("{} >>> {}", request.getMethod(), request.getRequestURL().toString());

        //得到头信息
        String token = request.getHeader("token");
        logger.info("》》》》》 token："+token);
        if(token== null){
            logger.warn("Token is empty");
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.getResponse().setContentType("application/json; charset=utf-8");
            String result = "{\"code\":\"401\",\"message\":\"请登录\"}";
            try {
                context.getResponse().getWriter().print(result);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else{
            if(!redisUtil.hasKey(token)){
                logger.warn("Token is empty");
                context.setSendZuulResponse(false);
                context.setResponseStatusCode(401);
                context.getResponse().setContentType("application/json; charset=utf-8");
                String result = "{\"code\":\"401\",\"message\":\"请重新登录\"}";
                try {
                    context.getResponse().getWriter().print(result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                logger.info("Token is OK");
                redisUtil.expire(token,60*60*24*7);
            }
        }




        return null;
    }
}